package com.kaikeba.servlet.handler.adapter;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaikeba.servlet.adapter.annotation.ResponseBody;
import com.kaikeba.servlet.adapter.utils.JsonUtil;
import com.kaikeba.servlet.handlermapping.impl.HandMethod;

public class RequestHandlerAdapter implements HandlerAdapter {

	@Override
	public void dohandlerRequest(Object handler, HttpServletRequest req, HttpServletResponse resp) {
		if (handler instanceof HandMethod) {
			Object obj = ((HandMethod) handler).getHandler();
			Method method = ((HandMethod) handler).getMethod();
			Object[] args = getParameters(req, method);
			try {
				Object returnValue = method.invoke(obj, args);
				handleReturnValue(returnValue, resp, method);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean isSuport(Object handler) {
		if (handler instanceof HandMethod) {
			return true;
		}
		return false;
	}

	private void handleReturnValue(Object returnValue, HttpServletResponse response, Method method) {
		try {
			if (method.isAnnotationPresent(ResponseBody.class)) {
				// 响应数据（前后端分离）
				if (returnValue instanceof String) {
					response.setContentType("text/plain;charset=utf8");
					response.getWriter().write(returnValue.toString());
				} else if (returnValue instanceof Map) {
					response.setContentType("application/json;charset=utf8");
					 response.getWriter().write(JsonUtil.object2Json(returnValue));
				}
			} else {
				// 展示视图
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Object[] getParameters(HttpServletRequest request, Method method) {
		// key=value&key1=value1.....
		// 获取请求URL中的参数信息
		Map<String, String[]> parameterMap = request.getParameterMap();
		// 获取handler方法的参数信息
		Parameter[] parameters = method.getParameters();

		List<Object> args = new ArrayList<>();
		for (Parameter parameter : parameters) {
			// 获取参数名称(如果不做特殊处理，name值是arg0，arg1)
			String name = parameter.getName();
			Class<?> type = parameter.getType();
			// 从url参数中获取指定名称的值
			String[] value = parameterMap.get(name);
			if (type == List.class) {
				args.add(value);
			} else if (type == Integer.class) {
				args.add(Integer.parseInt(value[0]));
			} else if (type == String.class) {
				args.add(value[0]);
			}
		}
		return args.toArray();
	}

}
